﻿/**********************************************************************
*创建人：蔡水明
*创建时间：2018/4/10 17:10:39
*说明：<Function>
/**********************************************************************/

using Newtonsoft.Json;
using Dapper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq.Expressions;
using DapperExtensions;

namespace Model
{
    public class BaseEntity<T> where T : class
    {
        /// <summary>
        /// 数据持久化操作的数据仓库类
        /// </summary>
        [JsonIgnore]
        public RespositoryBase<T> DataResp;       
        public BaseEntity()
        {
            DataResp = new RespositoryBase<T>();// IRespositoryBase<DbTest>();            
        }
        /// <summary>
        /// 获取默认的分页数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="expression"></param>
        /// <param name="sort"></param>
        /// <param name="page"></param>
        /// <param name="resultsPerPage"></param>
        /// <returns></returns>  
        public RespData GetDefLst(int page, int resultsPerPage)
        {
            int total = 0;
            RespData res = RespData.GetRes();
            var sortList = new List<ISort>();
            sortList.Add(new Sort { Ascending = false, PropertyName = "Id" });
            if (page < 1)
            {
                page = 1;
            }
            page -= 1;
            res.data = DataResp.Context.DB.GetPage<T>(null, sortList, page, resultsPerPage).ToList();
            total = DataResp.Context.DB.Count<T>(null);
            res.total = total;
            return res;
        }
        /// <summary>
        /// 数据库连接
        /// </summary>        
        public IDbConnection GetDBConn()
        {
            if (DataResp == null) return null;
            return DataResp.Context.DB;
        }

        /* var transaction = DB.BeginTransaction();
         * var result = 0;
            try
            {
                var sql = _builder.Insert(entities.First(), primaryKey);
        result = DB.Execute(sql, entities, transaction, commandTimeout);
                transaction.Commit();
            }
            catch
            {
                transaction.Rollback();
            }
            finally
            {
                DB.Close();
            }
            return result;*/
        /// <summary>
        /// 数据库事务       
        /// </summary>        
        public IDbTransaction GetDBTransaction()
        {
            if (DataResp == null) return null;
            return DataResp.Context.DB.BeginTransaction();
        }
    }
}
